//
//  LEEStatusetDAL.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/26.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

import UIKit
private let expires_date_timeIntravel: Double = -7 * 24 * 60 * 60

class LEEStatusetDAL: NSObject {

    //首页加载的数据的迁移
    class func loadHomeData(sinceID: Int64 , MAX_ID: Int64 ,finish: @escaping ([[String : Any]]?) -> ()) {
    
        
        if sinceID == 1 && MAX_ID == 0 {
            
            let res = checkoutStatus(sinceID: sinceID, MAX_ID: MAX_ID)
            if let result = res , result.count > 0 {
                //有缓存数据  返回缓存数据
                //TODO: 待返回
                finish(result)
                return
            }
            
        }
        
        //没有缓存数据, 请求网络数据
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        // access_token : 2.00_BsWNGtCSN7Bdcc71c1c9f2uDyCE
        //这个拿到最新的刷新数量
        let parameters = ["access_token" : LEEOAuthViewModel.shared.access_token!,
                          "max_id" : "\(MAX_ID)",
            "since_id" : "\(sinceID)"]
        
//        let parameters2 = ["access_token" : LEEOAuthViewModel.shared.access_token!]
        
        LEEHTTPRequst.HTTPShared.request(method: .GET, urlString: url, parameters: parameters ) { (responseObject, error) in
            
            if error != nil {
                
                finish(nil)
                return
                
            }
            // print(responseObject)
            let responses = responseObject as! [String : Any]
            //尝试转换为字典类型的数组
            guard let statuses = responses["statuses"] as? [[String : Any]] else {
                
                finish(nil)
                return
            }
            //回调的网络 请求的结果
            finish(statuses)
            ////存储到本地
            cacheStatuses(array: statuses)
        }
    }
    
    
    //1.检查本地是否有缓存数据
    class func checkoutStatus(sinceID: Int64 , MAX_ID: Int64) -> [[String : Any]]? {
    
        guard let userID = LEEOAuthViewModel.shared.userInfo?.uid else {
            return nil
        }
        //会将数据库中所有的缓存数据都查找到
        var sql = "SELECT statuse FROM T_Statuses WHERE userID = \(userID) "
        //拼接sql
        //如果sinceId > 0 标识需要查找新数据
        if sinceID > 0 {
            
            sql += "AND weiboID > \(sinceID) "
        }
        if MAX_ID > 0 {
            
            sql += "AND weiboID < \(MAX_ID) "
        }
        //排序 降序
        sql += "ORDER BY weiboID DESC "
         //限制条数
        sql += "LIMIT 50"
        
        var arrayM = [[String : Any]]()
        
        LEESQLiteTools.shared.queue.inDatabase { (db) in
            
            guard let results = db!.executeQuery(sql, withArgumentsIn: nil) else{
              return
            }
            //逐条获取数据
            while results.next() {
            
                let statues = results.data(forColumn: "statuse")
                let dict = try! JSONSerialization.jsonObject(with: statues!, options: [])
        
                arrayM.append(dict as! [String : Any])
            }
            
        }
        
        return arrayM
    }
    
    //2. 如果本地有缓存数据 就直接返回本地的缓存数据,给用户节省流量,让用户在没有网络的情况可以浏览之前的内容
    
    //3. 没有缓存数据就请求网络数据 返回网络数据
    
    //4. 获取网络数据之后就应该立即存储网络数据
    class func cacheStatuses(array: [[String : Any]]) {
    
        //获取userId
        guard let userID = LEEOAuthViewModel.shared.userInfo?.uid else {
            print("用户没有登录")
            return;
        }
        //sql
        //如果在对应的主键下已经存在数据 就执行替换的操作
        let sql = "INSERT OR REPLACE INTO T_Statuses  (weiboID,statuse,userID) VALUES (?,?,?)"
        
            
            LEESQLiteTools.shared.queue.inTransaction { (db, backroll) in
            for item in array {
                
                let id = item["id"]!
                //数据库中能够存储的数据不能够是Foundation 需要将字典数据转换二进制数据存储到数据库中
                //如果是字典数据 在读取的时候会有问题
                let data = try! JSONSerialization.data(withJSONObject: item, options: [])
                
                let result = db!.executeUpdate(sql, withArgumentsIn: [id,data,userID])
                
                if result {
                   print("插入成功")
                }else{
                
                    print("插入失败")
                    backroll?.pointee = true
                }
            }
        }
        
    }
    
    
    //删除缓存的数据
    class func deleteCacheStatuses() {
    //根据设置的过期描述 和当期日期 计算需要删除的微博记录
        let expires_date = Date(timeIntervalSinceNow: expires_date_timeIntravel)
        
        let formater = dateFormater
        //设置本地化信息
        formater.locale = Locale(identifier: "en")
        formater.dateFormat = "yyyy-MM-dd HH:mm:ss"
        //获取日期的字符串
        let dateStr = formater.string(from: expires_date)
        
        let sql = "DELETE FROM T_Statuses WHERE create_date < ?"
        
        LEESQLiteTools.shared.queue.inTransaction { (db, backroll) in
            
            let res = db!.executeUpdate(sql, withArgumentsIn: [dateStr])
            
            if res {
            
                print("删除成功")
            }else{
            
                print("删除失败")
                backroll?.pointee = true
            }
            
        }
        
    }
}












